using AutoMapper;
using B.S.Medical.Domain.Doctor;
using B.S.Medical.ErrorCode;
using MediatR;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;
using B.S.Medical.Infrastructure.Interface;
using B.S.Medical.Api.Read.DTOS;
using B.S.Medical.Api.Read.Application.Command.Doctor;
using NLog;

namespace B.S.Medical.Api.Read.Application.Handler.Doctor
{
    /// <summary>
    /// 获取医生职称详情命令处理程序
    /// </summary>
    public class GetJobTitleHandler : IRequestHandler<GetJobTitleCommand, ApiResult<List<JobTitleDTO>>>
    {
        private readonly IBaseRepository<JobTitleModel> _jobTitleRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<GetJobTitleHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="jobTitleRepository">职称仓储</param>
        /// <param name="mapper">对象映射器</param>
        /// <param name="logger">日志记录器</param>
        public GetJobTitleHandler(IBaseRepository<JobTitleModel> jobTitleRepository, IMapper mapper, ILogger<GetJobTitleHandler> logger)
        {
            _jobTitleRepository = jobTitleRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理命令
        /// </summary>
        /// <param name="request">查询命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>职称详情</returns>
        public Task<ApiResult<List<JobTitleDTO>>> Handle(GetJobTitleCommand request, CancellationToken cancellationToken)
        {
            try
            {
                ApiResult<List<JobTitleDTO>> res = new ApiResult<List<JobTitleDTO>>();
                var jobtitles = _jobTitleRepository.GetAll().Where(a => !a.IsDeleted);
                res.Code = ApiEnum.Success;
                res.Msg = "处理获取职称请求成功";
                res.Data = _mapper.Map<List<JobTitleDTO>>(jobtitles.ToList());
                return Task.FromResult(res);

            }
            catch (System.Exception ex)
            {
                _logger.LogError(ex, "获取标签时发生错误");
                throw;
            }
        }
    }
}